<template>
  <a-form
    :model="formSearchParams"
    :style="{ marginBottom: '20px' }"
    layout="inline"
    @submit="doSearch"
  >
    <a-form-item field="appId" label="应用 id">
      <a-input
        v-model="formSearchParams.appId"
        placeholder="请输入应用 id"
        allow-clear
      />
    </a-form-item>
    <a-form-item field="userId" label="用户 id">
      <a-input
        v-model="formSearchParams.userId"
        placeholder="请输入用户 id"
        allow-clear
      />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit" style="width: 100px">
        搜索
      </a-button>
    </a-form-item>
  </a-form>
  <a-table
    :columns="columns"
    :data="dataList"
    :pagination="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total,
    }"
    @page-change="onPageChange"
  >
    <template #questionContent="{ record }">
      <div v-if="record && record.questionContent">
        <!-- 展示前两个题目 -->
        <div
          v-for="(question, index) in getQuestions(record).slice(0, 2)"
          :key="index"
        >
          <p>{{ question.title }}</p>
        </div>
        <!-- 如果有更多题目，则显示查看全部按钮 -->
        <a-button
          @click="showAllQuestions(record)"
          v-if="getQuestions(record).length > 2"
          >查看全部</a-button
        >
      </div>
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>
  <a-modal
    v-model:visible="allQuestionsVisible"
    title="全部题目"
    :footer="null"
    @cancel="closeModal"
  >
    <div v-if="selectedRecord && selectedRecord.questionContent">
      <div
        v-for="(question, index) in getQuestions(selectedRecord)"
        :key="index"
      >
        <p>{{ question.title }}</p>
        <ul>
          <li v-for="(option, optIndex) in question.options" :key="optIndex">
            {{ option.key }}：{{ option.value }} - (分值: {{ option.score }})
          </li>
        </ul>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watchEffect } from "vue";
import {
  deleteQuestionUsingPost,
  listQuestionByPageUsingPost,
} from "@/api/questionController";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";

const formSearchParams = ref<API.QuestionQueryRequest>({});

// 初始化搜索条件（不应该被修改）
const initSearchParams = {
  current: 1,
  pageSize: 4,
};

const searchParams = ref<API.QuestionQueryRequest>({
  ...initSearchParams,
});
const dataList = ref<API.Question[]>([]);
const total = ref<number>(0);

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listQuestionByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

/**
 * 执行搜索
 */
const doSearch = () => {
  searchParams.value = {
    ...initSearchParams,
    ...formSearchParams.value,
  };
};

/**
 * 当分页变化时，改变搜索条件，触发数据加载
 * @param page
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 删除
 * @param record
 */
const doDelete = async (record: API.Question) => {
  if (!record.id) {
    return;
  }

  const res = await deleteQuestionUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    loadData();
  } else {
    message.error("删除失败，" + res.data.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

// 表格列配置
const columns = [
  {
    title: "id",
    dataIndex: "id",
  },
  {
    title: "题目内容",
    dataIndex: "questionContent",
    slotName: "questionContent",
  },
  {
    title: "应用 id",
    dataIndex: "appId",
  },
  {
    title: "用户 id",
    dataIndex: "userId",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    slotName: "createTime",
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    slotName: "updateTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

// 弹窗相关状态
const allQuestionsVisible = ref(false);
const selectedRecord = ref<API.Question | null>(null);

/**
 * 显示所有题目
 * @param record 当前行的数据
 */
const showAllQuestions = (record: API.Question) => {
  selectedRecord.value = record;
  allQuestionsVisible.value = true;
};

/**
 * 关闭模态框
 */
const closeModal = () => {
  allQuestionsVisible.value = false;
};

/**
 * 获取经过验证的题目列表
 * @param record 当前行的数据
 * @returns 题目列表
 */
const getQuestions = (record: API.Question): API.Question[] => {
  if (!record || !record.questionContent) {
    return [];
  }

  try {
    // 尝试解析 JSON 字符串
    const questions = JSON.parse(record.questionContent);
    // 确保解析结果是一个数组
    if (Array.isArray(questions)) {
      return questions;
    } else {
      console.error(
        "questionContent 解析结果不是数组:",
        record.questionContent
      );
      return [];
    }
  } catch (error) {
    console.error("解析 questionContent 失败:", error);
    return [];
  }
};
</script>
